<template>
  <NavBar title="代理系统" color="#fff" colorText="#333" brg="#f8f8f8">
  <view class="agent-apply-container">
    <!-- 内容区域 -->
    <view class="content-area">
      <!-- 提示信息 -->
      <view class="intro-section">
        <text class="intro-title">您暂未申请为代理系统</text>
        <text class="intro-desc">请填写相关信息,申请成为代理</text>
      </view>

      <!-- 表单区域 -->
      <view class="form-section">
        <view class="input-group">
          <input
            class="form-input"
            placeholder="请输入代理商名称"
            v-model="formData.agentName"
          />
        </view>

        <view class="input-group">
          <input
            class="form-input"
            placeholder="请输入联系人"
            v-model="formData.contactPerson"
          />
        </view>

        <view class="input-group">
          <input
            class="form-input"
            placeholder="请输入联系电话"
            v-model="formData.contactPhone"
            type="number"
          />
        </view>

        <view class="input-group">
          <textarea
            class="form-textarea"
            placeholder="请输入申请原因"
            v-model="formData.applicationReason"
          ></textarea>
        </view>
      </view>

      <!-- 申请规则 -->
      <view class="rules-section">
        <text class="rules-title">代理商申请规则:</text>
        <text class="rules-content" v-for="(rule, index) in agentRules" :key="index">{{ rule }}</text>
      </view>
    </view>

    <!-- 申请按钮 -->
    <view class="apply-button" @click="submitApplication">
      <text class="apply-text">申请代理商</text>
    </view>

    <!-- 登录弹窗组件 -->
    <LoginModal
      ref="loginModalRef"
      @close="onLoginModalClose"
      @skip="onLoginSkip"
      @login="onLoginSuccess"
    />
  </view>
  </NavBar>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { AGENT_API } from '../../config/api.js'
import { isLoggedIn, getToken, fetchUserInfo } from '../../utils/user.js'
import { isWeixinMiniProgram } from '../../utils/platform.js'
import { getRuleConfig } from '../../utils/config.js'
import LoginModal from '../../components/LoginModal/LoginModal.vue'

// 表单数据
const formData = ref({
  agentName: '',
  contactPerson: '',
  contactPhone: '',
  applicationReason: ''
})

// 登录弹窗引用
const loginModalRef = ref()

// 代理商申请规则
const agentRules = ref([
  '1. 代理商信息申请通过后无法更改,请谨慎填写。'
])

// 加载代理商申请规则
const loadAgentRules = async () => {
  try {
    const ruleConfig = await getRuleConfig(false)
    console.log('代理商申请规则配置:', ruleConfig)

    // 读取 agent_rule 字段
    if (ruleConfig.agent_rule) {
      // 根据 \n 分割规则
      const rules = ruleConfig.agent_rule.split('\n').filter(rule => rule.trim() !== '')
      if (rules.length > 0) {
        agentRules.value = rules
        console.log('代理商申请规则加载成功:', rules)
      } else {
        console.log('没有配置代理商申请规则，使用默认规则')
      }
    } else {
      console.log('没有配置 agent_rule 字段，使用默认规则')
    }
  } catch (error) {
    console.error('加载代理商申请规则失败:', error)
    // 使用默认规则
  }
}

// 页面加载时加载规则
onMounted(() => {
  loadAgentRules()
})

// 代理商名称格式验证
const validateAgentName = (name) => {
  // 只允许中文字符和空格
  const chineseAndSpaceRegex = /^[\u4e00-\u9fa5\s]+$/

  // 检查长度（2-20个字符）
  if (name.length < 2 || name.length > 20) {
    return {
      valid: false,
      message: '代理商名称长度应为2-20个字符'
    }
  }

  // 检查是否只包含中文字符和空格
  if (!chineseAndSpaceRegex.test(name)) {
    return {
      valid: false,
      message: '代理商名称只能包含中文字符和空格'
    }
  }

  return {
    valid: true,
    message: ''
  }
}

// 联系人名称格式验证
const validateContactPerson = (contact) => {
  // 只允许中文字符，不允许空格
  const chineseOnlyRegex = /^[\u4e00-\u9fa5]+$/

  // 检查长度（2-4个字符）
  if (contact.length < 2 || contact.length > 4) {
    return {
      valid: false,
      message: '联系人名称长度应为2-4个字符'
    }
  }

  // 检查是否只包含中文字符（不允许空格）
  if (!chineseOnlyRegex.test(contact)) {
    return {
      valid: false,
      message: '联系人名称只能包含中文字符（不允许空格）'
    }
  }

  return {
    valid: true,
    message: ''
  }
}

// 电话号码格式验证
const validatePhoneNumber = (phone) => {
  const phoneRegex = /^1[3-9]\d{9}$/
  return phoneRegex.test(phone)
}

// 申请原因格式验证
const validateApplicationReason = (reason) => {
  // 允许中文字符、标点符号、空格
  const chinesePunctuationSpaceRegex = /^[\u4e00-\u9fa5\u3000-\u303f\uff00-\uffef\s]+$/

  // 检查长度（2-40个字符）
  if (reason.length < 2 || reason.length > 40) {
    return {
      valid: false,
      message: '申请原因长度应为2-40个字符'
    }
  }

  // 检查是否只包含中文字符、标点符号、空格
  if (!chinesePunctuationSpaceRegex.test(reason)) {
    return {
      valid: false,
      message: '申请原因只能包含中文字符、标点符号、空格'
    }
  }

  return {
    valid: true,
    message: ''
  }
}

// 显示登录弹窗
const showLoginModal = () => {
  if (loginModalRef.value) {
    loginModalRef.value.open()
  }
}

// 跳转到登录页面
const navigateToLogin = (redirectUrl) => {
  uni.navigateTo({
    url: `/pages/login/login?redirect=${encodeURIComponent(redirectUrl)}`,
    fail: (error) => {
      console.error('跳转登录页面失败:', error)
      uni.showToast({
        title: '跳转失败',
        icon: 'none'
      })
    }
  })
}

// 登录弹窗事件处理
const onLoginModalClose = () => {
  console.log('登录弹窗关闭')
}

const onLoginSkip = () => {
  uni.showToast({
    title: '暂不登录',
    icon: 'none',
    duration: 2000
  })
}

const onLoginSuccess = () => {
  // 弹框处理了登录逻辑 这里只处理登录完成逻辑
  console.log('登录成功，可以继续申请代理商')
  uni.showToast({
    title: '登录成功',
    icon: 'success',
    duration: 2000
  })
}

// 提交申请
const submitApplication = async () => {
  // 1. 表单验证
  if (!formData.value.agentName.trim()) {
    uni.showToast({
      title: '请输入代理商名称',
      icon: 'none'
    })
    return
  }

  // 代理商名称格式验证
  const agentNameValidation = validateAgentName(formData.value.agentName.trim())
  if (!agentNameValidation.valid) {
    uni.showToast({
      title: agentNameValidation.message,
      icon: 'none'
    })
    return
  }

  if (!formData.value.contactPerson.trim()) {
    uni.showToast({
      title: '请输入联系人',
      icon: 'none'
    })
    return
  }

  // 联系人名称格式验证
  const contactPersonValidation = validateContactPerson(formData.value.contactPerson.trim())
  if (!contactPersonValidation.valid) {
    uni.showToast({
      title: contactPersonValidation.message,
      icon: 'none'
    })
    return
  }

  if (!formData.value.contactPhone.trim()) {
    uni.showToast({
      title: '请输入联系电话',
      icon: 'none'
    })
    return
  }

  // 2. 电话号码格式验证
  if (!validatePhoneNumber(formData.value.contactPhone)) {
    uni.showToast({
      title: '请输入正确的手机号码',
      icon: 'none'
    })
    return
  }

  if (!formData.value.applicationReason.trim()) {
    uni.showToast({
      title: '请输入申请原因',
      icon: 'none'
    })
    return
  }

  // 申请原因格式验证
  const reasonValidation = validateApplicationReason(formData.value.applicationReason.trim())
  if (!reasonValidation.valid) {
    uni.showToast({
      title: reasonValidation.message,
      icon: 'none'
    })
    return
  }

  // 3. 检查登录状态
  const loginStatus = isLoggedIn()
  if (!loginStatus) {
    // 判断是否为微信小程序
    if (isWeixinMiniProgram()) {
      // 微信小程序显示登录弹窗
      showLoginModal()
    } else {
      // 其他平台跳转到登录页面
      navigateToLogin('/pages/agent-apply/agent-apply')
    }
    return
  }

  // 4. 调用申请接口
  try {
    uni.showLoading({
      title: '提交中...'
    })

    const token = getToken()
    const requestData = {
      name: formData.value.agentName.trim(),
      contact: formData.value.contactPerson.trim(),
      mobile: formData.value.contactPhone.trim(),
      reason: formData.value.applicationReason.trim()
    }

    const response = await uni.request({
      url: AGENT_API.APPLY,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      data: requestData
    })

    uni.hideLoading()

    if (response.statusCode === 200 && response.data.code === 200) {
      // 申请成功
      uni.showToast({
        title: '申请提交成功',
        icon: 'success',
        duration: 2000
      })

      // 跳转到审核中页面，关闭当前页面
      uni.redirectTo({
        url: '/pages/agent-review/agent-review'
      })
      // 刷新用户信息
      try {
        await fetchUserInfo()
        console.log('用户信息刷新成功')
      } catch (error) {
        console.error('刷新用户信息失败:', error)
      }

    } else {
      // 申请失败
      const errorMessage = response.data?.data?.error_message || response.data?.error_message || response.data?.message || '申请失败，请重试'
      uni.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 3000
      })
    }

  } catch (error) {
    uni.hideLoading()
    console.error('申请代理商失败:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none',
      duration: 3000
    })
  }
}
</script>

<style scoped>
.agent-apply-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #C2DDFF  0%, #FFFFFF 100%);
  padding-top: 160rpx;
}

/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 40rpx 0;
  height: 88rpx;
}

.time {
  font-size: 32rpx;
  font-weight: 600;
  color: #000000;
}

.status-icons {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.signal-icon,
.wifi-icon,
.battery-icon {
  width: 24rpx;
  height: 16rpx;
  background: #000000;
  border-radius: 2rpx;
}

.battery-icon {
  width: 32rpx;
  height: 16rpx;
  position: relative;
}

.battery-icon::after {
  content: '';
  position: absolute;
  right: -6rpx;
  top: 50%;
  transform: translateY(-50%);
  width: 4rpx;
  height: 8rpx;
  background: #000000;
  border-radius: 0 2rpx 2rpx 0;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 40rpx;
  height: 88rpx;
}

.nav-left {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 48rpx;
  font-weight: 300;
  color: #000000;
  line-height: 1;
}

.nav-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #000000;
  flex: 1;
  text-align: center;
  margin-left: -60rpx;
}

.nav-right {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.placeholder-btn {
  width: 40rpx;
  height: 30rpx;
  background: #F5F5F5;
  border-radius: 15rpx;
}

/* 内容区域 */
.content-area {
  padding: 40rpx;
  flex: 1;
}

/* 提示信息 */
.intro-section {
  margin-bottom: 60rpx;
}

.intro-title {
  display: block;
  font-size: 36rpx;
  font-weight: 500;
  color: #333333;
  margin-bottom: 16rpx;
}

.intro-desc {
  display: block;
  font-size: 28rpx;
  color: #999999;
  line-height: 1.5;
}

/* 表单区域 */
.form-section {
  margin-bottom: 60rpx;
}

.input-group {
  margin-bottom: 30rpx;
}

.form-input {
  width: 100%;
  height: 88rpx;
  background: #FFFFFF;
  border: 2rpx solid #E0E0E0;
  border-radius: 12rpx;
  padding: 0 24rpx;
  font-size: 32rpx;
  color: #333333;
  box-sizing: border-box;
}

.form-input::placeholder {
  color: #CCCCCC;
}

.form-textarea {
  width: 100%;
  height: 160rpx;
  background: #FFFFFF;
  border: 2rpx solid #E0E0E0;
  border-radius: 12rpx;
  padding: 24rpx;
  font-size: 32rpx;
  color: #333333;
  box-sizing: border-box;
  resize: none;
}

.form-textarea::placeholder {
  color: #CCCCCC;
}

/* 申请规则 */
.rules-section {
  margin-bottom: 40rpx;
}

.rules-title {
  display: block;
  font-size: 32rpx;
  font-weight: 500;
  color: #333333;
  margin-bottom: 16rpx;
}

.rules-content {
  display: block;
  font-size: 28rpx;
  color: #999999;
  line-height: 1.5;
}

/* 申请按钮 */
.apply-button {
  position: fixed;
  bottom: 40rpx;
  left: 40rpx;
  right: 40rpx;
  height: 88rpx;
  background: linear-gradient(135deg, #8B5CF6 0%, #3B82F6 100%);
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(139, 92, 246, 0.3);
}

.apply-text {
  font-size: 36rpx;
  font-weight: 600;
  color: #FFFFFF;
}
</style>

